package com.share.three.netty.fixedLength;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/*
 * 采用分隔符的方式解决拆包粘包的问题：  DelimiterBasedFrameDecoder
 */
public class Client {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.option(ChannelOption.SO_BACKLOG, 1024);
			b.option(ChannelOption.SO_RCVBUF, 32*1024);
			b.option(ChannelOption.SO_SNDBUF, 32*1024);
			b.handler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					//设置定长---->不够指定长短不会发送
					ch.pipeline().addLast(new FixedLengthFrameDecoder(5));
					//设置字符串形式的解码--->读可以，写还要bytebuf
					ch.pipeline().addLast(new StringDecoder());
					ch.pipeline().addLast(new ClientHandler());
				}
			});
			
			ChannelFuture f = b.connect("127.0.0.1", 12345).sync();
			
			f.channel().writeAndFlush(Unpooled.copiedBuffer("aaaaabbbb你".getBytes()));
			f.channel().writeAndFlush(Unpooled.copiedBuffer("ccccccc   $".getBytes()));
			
			f.channel().closeFuture().sync();
			
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			workerGroup.shutdownGracefully();
		}
	}

}
